package tbdp.tool;

import com.google.common.base.Preconditions;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import tbdp.tool.common.Utils;
import tbdp.tool.common.ZipUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by xbkaishui on 17/3/18.
 */
public class TxtFileReader {

    private static Logger logger = Logger.getLogger(TxtFileReader.class);

    private final static String fieldSep = "\\|";

    /**
     * 读取行情 txtfile 需要做以下逻辑
     * 1.补全状态字段,从第一行头里面获取
     *
     * @param file
     * @param charset
     * @return
     */
    public static List<List<String>> readFile(File file, String charset) {
        Charset cs = Charset.forName(charset);
        List<List<String>> result = new LinkedList<>();
        File realFile = file;
        InputStream ins = null;
        try {
            //判断是不是zip文件
            if (file.getName().endsWith(".zip")) {
                List<File> fileList = ZipUtil.decompress(file);
                Preconditions.checkArgument(fileList.size() == 1, "zip文件里面文件个数多于一个" + fileList);
                realFile = fileList.get(0);
            }
            ins = new FileInputStream(realFile);
            List<String> lines = IOUtils.readLines(ins, cs);
            if (CollectionUtils.isNotEmpty(lines)) {
                String headers[] = lines.get(0).split(fieldSep);
                int len = headers.length;
                String status = headers[len - 1];
                String mdTime = headers[len - 3];

                for (int i = 1; i < lines.size(); i++) {
                    List<String> record = new LinkedList<>();
                    String fields[] = lines.get(i).split(fieldSep);
                    for (String field : fields) {
                        record.add(field.trim());
                    }
                    record.add(mdTime);
                    record.add(status);
                    result.add(record);
                }
            } else {
                logger.warn("empty file content " + realFile.getAbsolutePath());
            }
        } catch (Exception e) {
            throw new RuntimeException(file.getAbsolutePath(), e);
        } finally {
            IOUtils.closeQuietly(ins);
            Utils.deleteFilesOnExit(realFile);
        }
        return result;
    }

}
